import 'dart:ui';

import 'package:flame/components/component.dart';
import 'package:flame/gestures.dart';
import 'package:flutter/material.dart';
import 'package:hello_flutter/demo/game/game_state.dart';

import '../game_controller.dart';

class Enemy extends Component with TapDetector {
  final GameController controller; // 控制器
  Rect enemyRect; // 敌人
  int heath; // 生命值
  int damage; // 损伤
  double speed; // 移动速度
  bool isDead = false; // 是否死亡

  Enemy(this.controller, double x, double y) {
    heath = 3;
    damage = 1;
    speed = controller.tileSize * 2;
    enemyRect = Rect.fromLTWH(
        x, y, controller.tileSize * 1.2, controller.tileSize * 1.2);
  }

  @override
  void render(Canvas canvas) {
    Color color;
    switch (heath) {
      case 1:
        color = Color(0xffff7f7f);
        break;
      case 1:
        color = Color(0xffff4c4c);
        break;
      case 1:
        color = Color(0xffff4500);
        break;
      default:
        color = Color(0xffff0000);
        break;
    }
    final enemyColor = Paint()..color = color;
    canvas.drawRect(enemyRect, enemyColor);
  }

  @override
  void update(double time) {
    // 如果还没死
    if (!isDead) {
      final stepDistance = speed * time; // 移动距离 = 速度 * 时间
      // 得到中心点距离
      Offset toPlayer = controller.player.playRect.center - enemyRect.center;
      // 触碰到边缘
      if (stepDistance <= toPlayer.distance - controller.tileSize * 1.3) {
        // 到玩家的步数
        final stepToPlayer =
            Offset.fromDirection(toPlayer.direction, stepDistance);
        enemyRect = enemyRect.shift(stepToPlayer); // 敌人偏移坐标至玩家
      } else {
        attack();
      }
    }
  }

  @override
  void onTapDown(TapDownDetails details) {
    if (!isDead) {
      heath--;
      if (heath <= 0) {
        isDead = true;
        controller.score++;
        if (controller.score > (controller.storage.getInt(SCORE_KEY) ?? 0)) {
          controller.storage.setInt(SCORE_KEY, controller.score);
        }
      }
    }
    super.onTapDown(details);
  }

  void attack() {
    // 判断玩家死亡状态
    if (!controller.player.isDead) {
      controller.player.currentHeath -= damage; // 掉血(玩家受伤后当前生命值)
    }
  }
}
